import { FC, useState, useEffect, useMemo, useRef } from 'react';
import { OneModal } from '@/components/one-ui';
import { Button, Col, Form, Input, message, Row, Select, Table, Tooltip, TreeSelect } from 'antd';
import { SchemaManage } from '@/components/SchemaComponent';
import { getKeyRouter, getLoadMapList, getTenantID, tooltipLength } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { SearchOutlined, ReloadOutlined, AuditOutlined, SoundOutlined } from '@ant-design/icons';
import { BZWC_STATE, CQXG_STATE, ColumnsRenderFun, getSorter, setTableRowClassName } from '../common/Format';
import { applyManageService } from '../services/UpdataModalService';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';
import pageStyles from '@/common/pageLayout.less';
import { formatDecimal } from '../../Acommon';
import { history } from 'umi';
export const UpdataApplyModal: any = ({ onClose, curRes, locationProps }) => {
  // 获取数据
  const { getProjectService } = applyManageService(curRes);
  let { getProjectRun, getProjectLoading, getProjectPagination } = getProjectService();
  // 字典id集合
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`,
    `${getTenantID()}${ILoadMapTypeAll.CURRYOUT_STATE}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`,
  ];
  // 请求字典
  const { loadMapInfo } = getLoadMapList(loadMdicIds);
  // 确定
  const onUpdataMaterial = () => {};
  // 公告
  const noticeSubmit = async (val: any) => {
    await onClose();
    history.push({
      pathname: `/purchaseSourceController/addBid/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        type: 'edit',
        info: val,
        sourceKey: true,
        returnPathName: locationProps?.pathname,
      },
    });
  };
  // 澄清
  const clearTimeout = (val: any) => {
    onClose();
    history.push({
      pathname: `/purchaseSourceClarifyController/add/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        type: 'clarify',
        info: val,
        sourceKey: true,
        returnPathName: locationProps?.pathname,
      },
    });
  };
  // 查询条件表单实例
  const [searchForm] = Form.useForm();
  const columns: any = [
    {
      title: '承办部门/团队', // 原【申请部门】
      dataIndex: 'applyDepartmentName',
      key: 'applyDepartmentName',
      visible: true,
      fixed: 'left',
      sorter: (a: any, b: any) => getSorter(a?.applyDepartmentName, b?.applyDepartmentName),
      width: 170,
      render: (text: string) => ColumnsRenderFun({ text, isTooltip: true }),
    },
    {
      title: '采购项目名称',
      dataIndex: 'applyTitle',
      key: 'applyTitle',
      visible: true,
      width: 220,
      fixed: 'left',
      sorter: (a: any, b: any) => getSorter(a?.applyTitle, b?.applyTitle),
      render: (text: string, record: Record<string, any>) => {
        return (
          <Tooltip title={tooltipLength(text, 50)}>
            <span className={pageStyles['over-flow-hidden']}>{text || '--'}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '预算费用（元）',
      dataIndex: 'expectSum',
      key: 'expectSum',
      visible: true,
      sorter: (a: any, b: any) => getSorter(a?.expectSum, b?.expectSum),
      width: 150,
      render: (text: string) => <span>{formatDecimal(text)}</span>,
    },
    {
      title: '标的来源',
      dataIndex: 'supplyWay',
      key: 'supplyWay',
      visible: true,
      sorter: (a: any, b: any) => getSorter(a?.supplyWay, b?.supplyWay),
      width: 150,
      render: (text: string | number) => {
        return <div>{text == 0 ? '月度计划' : text == 1 ? '零星采购' : text == 2 ? '实验平台' : '--'}</div>;
      },
    },
    {
      title: '公告编号',
      dataIndex: 'noticeCode',
      key: 'noticeCode',
      visible: true,
      sorter: (a: any, b: any) => getSorter(a?.noticeCode, b?.noticeCode),
      width: 150,
      render: (text: string, record: Record<string, any>) => {
        return (
          <Tooltip title={tooltipLength(text, 50)}>
            <span className={pageStyles['over-flow-hidden']}>{text || '--'}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '公告名称',
      dataIndex: 'noticeName',
      key: 'noticeName',
      visible: true,
      sorter: (a: any, b: any) => getSorter(a?.noticeName, b?.noticeName),
      width: 150,
      render: (text: string, record: Record<string, any>) => {
        return (
          <Tooltip title={tooltipLength(text, 50)}>
            <span className={pageStyles['over-flow-hidden']}>{text || '--'}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建人',
      dataIndex: 'createrName',
      key: 'createrName',
      sorter: (a: any, b: any) => getSorter(a?.createrName, b?.createrName),
      width: 120,
      visible: true,
      render: (text: string) => ColumnsRenderFun({ text }),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: (a: any, b: any) => getSorter(a?.createTime, b?.createTime),
      width: 150,
      visible: true,
      render: (text: string | null) => {
        return <span>{text ? text?.split(' ')?.[0] : '--'}</span>;
      },
    },
    {
      title: '操作',
      width: 100,
      visible: true,
      fixed: 'right',
      render: (text: any, record) => {
        return (
          <>
            {text?.state == BZWC_STATE() && curRes?.['/purchaseSourceController/addBid'] && (
              <Button
                icon={<AuditOutlined />}
                className="manageBtntTxtStyle"
                type={'link'}
                size={'small'}
                onClick={() => {
                  noticeSubmit(record);
                }}
              >
                公告
              </Button>
            )}
            {text?.state == CQXG_STATE() && curRes?.['/purchaseSourceClarifyController/add'] && (
              <Button
                icon={<SoundOutlined />}
                className="manageBtntTxtStyle"
                type={'link'}
                size={'small'}
                onClick={() => {
                  clearTimeout(record);
                }}
              >
                澄清
              </Button>
            )}
          </>
        );
      },
    },
  ];
  // 表格数据
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);
  // 树形选择
  const fieldNames = {
    label: 'name',
    value: 'id',
  };
  // 公告名称是否显示
  const [isShowNews, setIsShowNews] = useState<boolean>(false);
  const getListInfo = async (params: any) => {
    const { rows, msgFlag, msg } = await getProjectRun(params);
    if (msgFlag) {
      message.success(msg);
      rows?.forEach((item) => {
        item.applyDepartmentName = item?.mpurchaseApply.applyDepartmentName;
        item.applyTitle = item?.mpurchaseApply.applyTitle;
        item.expectSum = item?.mpurchaseApply.expectSum;
        item.supplyWay = item?.mpurchaseApply.supplyWay;
        item.createrName = item?.mpurchaseApply.createrName;
        item.createTime = item?.mpurchaseApply.createTime;
        item.applyID = item?.mpurchaseApply.id;
      });
      setDataSource(rows);
      return rows;
    } else {
      message.warning(msg);
    }
  };
  // 获取所有项目列表
  const fetchGetProjectList = (params?: any) => {
    searchForm?.validateFields()?.then(async (values: any) => {
      getListInfo(params ? params : values);
    });
  };
  /** 表格分页方法改变事件 */
  const handlePaginationChange = (current, pageSize, params) => {
    let state = searchForm.getFieldValue('state') ? searchForm.getFieldValue('state') : '100122141010,100122141004';
    getListInfo({ pageSize, current, ...params, ...searchForm.getFieldsValue(), state });
  };
  useEffect(() => {
    getListInfo({});
  }, []);
  return (
    <div>
      <OneModal
        open={true}
        getContainer={false}
        title={'采购申请信息'}
        width={1100}
        onCancel={onClose}
        onOk={onUpdataMaterial}
        bodyStyle={{ padding: '5px 10px', height: document.body.clientHeight * 0.6 }}
        footer={<></>}
      >
        <div className={'ProjectModalSearch'}>
          <Form form={searchForm}>
            <Row gutter={[8, 0]}>
              <Col span={4}>
                <Form.Item name={'applyName'}>
                  <Input placeholder="采购项目名称" allowClear />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name={'procureReal'} rules={[{ required: true, message: '请选择拟采方式' }]}>
                  <TreeSelect
                    placeholder="拟采方式"
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    allowClear
                    fieldNames={fieldNames}
                    treeDefaultExpandAll
                    treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]}
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name={'state'} rules={[{ required: true, message: '请选择状态' }]}>
                  <Select
                    placeholder="状态"
                    onChange={(val: any) => {
                      if (val == '100122141004') {
                        setIsShowNews(true);
                      } else {
                        setIsShowNews(false);
                      }
                    }}
                    allowClear
                    options={[
                      { value: '100122141010', label: '待实施' },
                      { value: '100122141004', label: '澄清中' },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                {isShowNews && (
                  <Form.Item name={'noticeName'} rules={[{ required: true, message: '请输入公告名称' }]}>
                    <Input placeholder="公告名称" allowClear />
                  </Form.Item>
                )}
              </Col>
              <Col span={8} style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Form.Item>
                  <Button
                    type={'default'}
                    icon={<ReloadOutlined />}
                    onClick={() => {
                      searchForm.resetFields();
                      getListInfo({});
                    }}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: 0, float: 'right' }}
                  >
                    重置
                  </Button>
                  <Button
                    type={'primary'}
                    htmlType="submit"
                    icon={<SearchOutlined />}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: '8px', float: 'right' }}
                    onClick={() => {
                      fetchGetProjectList();
                    }}
                  >
                    查询
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        {/* <div className={`${prefixCls}-material-list list-table listTable-zIndexStyle`}> */}
        <div className={`list-table ProjectModalTable`}>
          <Table
            size="small"
            bordered
            scroll={{ x: 1000, y: 1000 }}
            style={{ margin: '0', height: document.body.clientHeight * 0.55 }}
            rowClassName={setTableRowClassName}
            loading={getProjectLoading}
            dataSource={dataSource}
            columns={columns}
            rowKey={'mockID'}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: commonPageSizeOptions,
              showTotal: showTotalInfo,
              ...getProjectPagination,
              onChange: handlePaginationChange as any,
              // pageSize: pageSize,
              // current: current,
              // total: total,
              // pageSize: 10,
              // current: 1,
              // total: 11,
            }}
          />
        </div>
      </OneModal>
    </div>
  );
};
